package com.csii.modules.online.cgform.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.csii.autopoi.poi.excel.ExcelExportUtil;
import com.csii.autopoi.poi.excel.ExcelImportUtil;
import com.csii.autopoi.poi.excel.entity.ExportParams;
import com.csii.autopoi.poi.excel.entity.ImportParams;
import com.csii.autopoi.poi.excel.entity.params.ExcelExportEntity;
import com.csii.core.annotation.AutoLog;
import com.csii.core.annotation.OnlineAuth;
import com.csii.core.annotation.PermissionData;
import com.csii.core.api.Result;
import com.csii.core.enums.ModuleType;
import com.csii.core.exception.AppException;
import com.csii.core.system.vo.DictModel;
import com.csii.core.util.BrowserUtils;
import com.csii.core.util.SpringContextUtils;
import com.csii.core.util.TokenUtils;
import com.csii.core.util.oConvertUtils;
import com.csii.modules.online.auth.service.IOnlAuthPageService;
import com.csii.modules.online.cgform.converter.ValueFillConverter;
import com.csii.modules.online.cgform.entity.OnlCgformEnhanceJs;
import com.csii.modules.online.cgform.entity.OnlCgformField;
import com.csii.modules.online.cgform.entity.OnlCgformHead;
import com.csii.modules.online.cgform.model.*;
import com.csii.modules.online.cgform.service.IOnlCgformFieldService;
import com.csii.modules.online.cgform.service.IOnlCgformHeadService;
import com.csii.modules.online.cgform.service.IOnlCgformSqlService;
import com.csii.modules.online.cgform.service.IOnlineService;
import com.csii.modules.online.cgform.table.TableComponent;
import com.csii.modules.online.cgform.util.EnhanceJsUtil;
import com.csii.modules.online.cgform.util.ExcelDataHandlerDefaultUtil;
import com.csii.modules.online.cgform.util.CgformSqlUtil;
import com.csii.modules.online.cgform.util.ZipUtils;
import com.csii.modules.online.config.exception.BusinessException;
import com.csii.modules.online.config.exception.DBException;
import com.csii.modules.online.config.util.DialectUtil;
import com.csii.modules.system.service.ISysBaseAPI;
import com.google.common.collect.Lists;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer;
import org.springframework.jdbc.support.incrementer.PostgresSequenceMaxValueIncrementer;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 在线生成
 * onlCgformApiController
 */
@RestController("onlCgformApiController")
@RequestMapping({"/online/cgform/api"})
public class CgformApiController {
	private static final Logger log = LoggerFactory.getLogger(CgformApiController.class);
	@Autowired
	private IOnlCgformHeadService onlCgformHeadService;
	@Autowired
	private IOnlCgformFieldService onlCgformFieldService;
	@Autowired
	private IOnlCgformSqlService onlCgformSqlService;
	@Autowired
	private IOnlAuthPageService onlAuthPageService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
	private IOnlineService onlineService;
	@Value("${stdio.path.upload}")
	private String upLoadPath;
	@Value("${stdio.uploadType}")
	private String uploadType;
	@Value("${cola.generate.path:/opt/temp/codegenerate/}")
	private String generatePath;

	/**
	 * 添加所有..
	 *
	 * @param model .
	 * @return Result .
	 */
	@PostMapping({"/addAll"})
	public Result<?> addAll(@RequestBody OnlCgformModel model) {
		try {
			String tableName = model.getHead().getTableName();
			return DialectUtil.isTableExists(tableName) ? Result.error("数据库表[" + tableName + "]已存在,请从数据库导入表单") : this.onlCgformHeadService.addAll(model);
		} catch (Exception var3) {
			log.error("OnlCgformApiController.addAll()发生异常：" + var3.getMessage(), var3);
			return Result.error("操作失败");
		}
	}

	/**
	 * 编辑
	 *
	 * @param model
	 * @return Result
	 */
	@PutMapping({"/editAll"})
	public Result<?> editAll(@RequestBody OnlCgformModel model) {
		try {
			return this.onlCgformHeadService.editAll(model);
		} catch (Exception e) {
			log.error("OnlCgformApiController.editAll()发生异常：" + e.getMessage(), e);
			return Result.error("操作失败");
		}
	}

	@AutoLog(
			operateType = 1,
			value = "online列表加载",
			module = ModuleType.ONLINE
	)
	@OnlineAuth("getColumns")
	@GetMapping({"/getColumns/{code}"})
	public Result<OnlForeignKey.OnlComplexModel> getColumns(@PathVariable("code") String code) {
		Result result = new Result();
		OnlCgformHead head = (OnlCgformHead) this.onlCgformHeadService.getById(code);
		if (head == null) {
			result.error500("实体不存在");
			return result;
		} else {
			OnlForeignKey.OnlComplexModel model = this.onlineService.queryOnlineConfig(head);
			result.setResult(model);
			result.setOnlTable(head.getTableName());
			return result;
		}
	}

	@AutoLog(
			operateType = 1,
			value = "online列表数据查询",
			module = ModuleType.ONLINE
	)
	@PermissionData
	@OnlineAuth("getData")
	@GetMapping({"/getData/{code}"})
	public Result<Map<String, Object>> getDataByCode(@PathVariable("code") String code, HttpServletRequest request) {
		Result result = new Result();
		//查询head表ID是否存在
		OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(code);
		if (onlCgformHead == null) {
			result.error500("实体不存在");
			return result;
		} else {
			try {
				//获取表名
				String tableName = onlCgformHead.getTableName();
				//通过HttpServletRequest拿到参数
				Map parammap = CgformSqlUtil.paramToMap(request);
				Map resMap = this.onlCgformFieldService.queryAutolistPage(tableName, code, parammap, (List) null);
				this.executeEnhanceList(onlCgformHead, resMap);
				result.setResult(resMap);
			} catch (Exception var8) {
				log.error(var8.getMessage(), var8);
				result.error500("数据库查询失败，" + var8.getMessage());
			}

			result.setOnlTable(onlCgformHead.getTableName());
			return result;
		}
	}

	@AutoLog(
			operateType = 1,
			value = "online表单加载",
			module = ModuleType.ONLINE
	)
	@OnlineAuth("getFormItem")
	@GetMapping({"/getFormItem/{code}"})
	public Result<?> getFormItem(@PathVariable("code") String code, HttpServletRequest request) {
		OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(code);
		if (onlCgformHead == null) {
			return Result.error("表不存在");
		}
		Result re = new Result();
		OnlCgformEnhanceJs onlCgformEnhanceJs = this.onlCgformHeadService.queryEnhanceJs(code, "form");
		JSONObject var6 = this.onlineService.queryOnlineFormObj(onlCgformHead, onlCgformEnhanceJs);
		var6.put("formTemplate", onlCgformHead.getFormTemplate());
		if (onlCgformHead.getTableType() == 2) {
			JSONObject jsonObject = var6.getJSONObject("schema");
			String sttings = onlCgformHead.getSubTableStr();
			if (oConvertUtils.isNotEmpty(sttings)) {
				ArrayList list = new ArrayList();
				String[] var10 = sttings.split(",");
				int var11 = var10.length;

				for (int var12 = 0; var12 < var11; ++var12) {
					String var13 = var10[var12];
					OnlCgformHead var14 = (OnlCgformHead) this.onlCgformHeadService.getOne(Wrappers.lambdaQuery(OnlCgformHead.class).eq(OnlCgformHead::getTableName, var13));
					if (var14 != null) {
						list.add(var14);
					}
				}

				if (list.size() > 0) {
					Collections.sort(list, (Comparator<OnlCgformHead>) (var1, var2) -> {
						Integer var3 = var1.getTabOrderNum();
						if (var3 == null) {
							var3 = 0;
						}

						Integer var4 = var2.getTabOrderNum();
						if (var4 == null) {
							var4 = 0;
						}

						return var3.compareTo(var4);
					});
					Iterator var15 = list.iterator();

					while (var15.hasNext()) {
						OnlCgformHead one = (OnlCgformHead) var15.next();
						List var17 = this.onlCgformFieldService.queryAvailableFields(one.getId(), one.getTableName(), (String) null, false);
						EnhanceJsUtil.b(onlCgformEnhanceJs, one.getTableName(), var17);
						JSONObject jsonObj = new JSONObject();
						List var19 = this.onlAuthPageService.queryFormDisabledCode(one.getId());
						if (1 == one.getRelationType()) {
							//方法签名
							jsonObj = CgformSqlUtil.a((List) var17, (List) var19, (OnlFieldModel) null);
						} else {
							jsonObj.put("columns", CgformSqlUtil.parseViewConfig(var17, var19));
						}

						jsonObj.put("id", one.getId());
						jsonObj.put("describe", one.getTableTxt());
						jsonObj.put("key", one.getTableName());
						jsonObj.put("view", "tab");
						jsonObj.put("order", one.getTabOrderNum());
						jsonObj.put("relationType", one.getRelationType());
						jsonObject.getJSONObject("properties").put(one.getTableName(), jsonObj);
					}
				}
			}

			if (onlCgformEnhanceJs != null && oConvertUtils.isNotEmpty(onlCgformEnhanceJs.getCgJs())) {
				//工具类中方法签名待定
				var6.put("enhanceJs", EnhanceJsUtil.a(onlCgformEnhanceJs.getCgJs()));
			}
		}

		re.setResult(var6);
		re.setOnlTable(onlCgformHead.getTableName());
		return re;
	}

	/**
	 * @param table
	 * @param taskId
	 * @return
	 */
	@AutoLog(
			operateType = 1,
			value = "online根据表名加载表单",
			module = ModuleType.ONLINE
	)
	@GetMapping({"/getFormItemBytbname/{table}"})
	public Result<?> getFormItemBytbname(@PathVariable("table") String table, @RequestParam(name = "taskId", required = false) String taskId) {
		Result result = new Result();
		LambdaQueryWrapper<OnlCgformHead> wrapper = new LambdaQueryWrapper(OnlCgformHead.class);
		wrapper.eq(OnlCgformHead::getTableName, table);
		OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getOne(wrapper);
		if (onlCgformHead == null) {
			return Result.error("表不存在");
		}

		JSONObject jsonObj = new JSONObject();
		onlCgformHead.setTaskId(taskId);
		jsonObj.put("schema", this.onlCgformHeadService.queryFormItem(onlCgformHead));
		jsonObj.put("head", onlCgformHead);
		result.setResult(jsonObj);
		result.setOnlTable(table);
		return result;
	}

	/**
	 * @param code
	 * @param request
	 * @return
	 */
	@OnlineAuth("getEnhanceJs")
	@GetMapping({"/getEnhanceJs/{code}"})
	public Result<?> getEnhanceJs(@PathVariable("code") String code, HttpServletRequest request) {
		String str = "";
		OnlCgformEnhanceJs one = this.onlCgformHeadService.queryEnhanceJs(code, "form");
		if (one != null && oConvertUtils.isNotEmpty(one.getCgJs())) {
			str = EnhanceJsUtil.b(one.getCgJs(), (List) null);
		}

		return Result.ok(str);
	}

	@AutoLog(
			operateType = 1,
			value = "online表单数据查询")
	@GetMapping({"/form/{code}/{id}"})
	public Result<?> getFormByCodeID(@PathVariable("code") String code, @PathVariable("id") String id) {
		try {
			Map map = this.onlCgformHeadService.queryManyFormData(code, id);
			return Result.ok(CgformSqlUtil.query(map));
		} catch (Exception var4) {
			log.error("Online表单查询异常：" + var4.getMessage(), var4);
			return Result.error("查询失败，" + var4.getMessage());
		}
	}

	/**
	 * @param table
	 * @param mainId
	 * @return
	 */
	@GetMapping({"/subform/{table}/{mainId}"})
	public Result<?> subform(@PathVariable("table") String table, @PathVariable("mainId") String mainId) {
		try {
			Map map = this.onlCgformHeadService.querySubFormData(table, mainId);
			return Result.ok(CgformSqlUtil.query(map)); //util
		} catch (Exception e) {
			log.error("Online表单查询异常：" + e.getMessage(), e);
			return Result.error("查询失败，" + e.getMessage());
		}
	}

	@GetMapping({"/subform/list/{table}/{mainId}"})
	public Result<?> subformList(@PathVariable("table") String table, @PathVariable("mainId") String mainId) {
		try {
			return Result.ok(this.onlCgformHeadService.queryManySubFormData(table, mainId));
		} catch (Exception e) {
			log.error("Online表单查询异常：" + e.getMessage(), e);
			return Result.error("查询失败，" + e.getMessage());
		}
	}

	@AutoLog(
			operateType = 1,
			value = "online根据表名查询表单数据",
			module = ModuleType.ONLINE
	)
	/**
	 * get
	 */
	@GetMapping({"/form/table_name/{tableName}/{dataId}"})
	public Result<?> formByGet(@PathVariable("tableName") String tableName, @PathVariable("dataId") String dataId) {
		try {
			LambdaQueryWrapper<OnlCgformHead> wrapper = new LambdaQueryWrapper(OnlCgformHead.class);
			wrapper.eq(OnlCgformHead::getTableName, tableName);
			OnlCgformHead one = (OnlCgformHead) this.onlCgformHeadService.getOne(wrapper);
			if (one == null) {
				throw new Exception("OnlCgform tableName: " + tableName + " 不存在！");
			} else {

				//此处原来用到运行时多态，先将方法签名改动，可能会报错
				Result result = this.getFormByCodeID(one.getId(), dataId);
				result.setOnlTable(tableName);
				return result;
			}
		} catch (Exception e) {
			log.error("Online表单查询异常，" + e.getMessage(), e);
			return Result.error("查询失败，" + e.getMessage());
		}
	}

	@AutoLog(
			operateType = 2,
			value = "online新增数据",
			module = ModuleType.ONLINE
	)
	@OnlineAuth("form")
	@PostMapping({"/form/{code}"})
	public Result<String> formByPost(@PathVariable("code") String code, @RequestBody JSONObject obj, HttpServletRequest req) {
		Result result = new Result();

		try {
			String str = CgformSqlUtil.getId();
			obj.put("id", str);
			String var6 = TokenUtils.getTokenByRequest(req);
			String ontable = this.onlCgformHeadService.saveManyFormData(code, obj, var6);
			result.setSuccess(true);
			result.setResult(str);
			result.setOnlTable(ontable);
		} catch (Exception e) {
			log.error("OnlCgformApiController.formAdd()发生异常：", e);
			result.setSuccess(false);
			result.setMessage("保存失败，" + CgformSqlUtil.parseException(e));
		}

		return result;
	}

	@AutoLog(
			operateType = 3,
			value = "online修改数据",
			module = ModuleType.ONLINE
	)
	@OnlineAuth("form")
	@PutMapping({"/form/{code}"})
	public Result<?> formByPut(@PathVariable("code") String code, @RequestBody JSONObject obj) {
		try {
			String ontable = this.onlCgformHeadService.editManyFormData(code, obj);
			Result result = Result.ok("修改成功！");
			result.setOnlTable(ontable);
			return result;
		} catch (Exception e) {
			log.error("OnlCgformApiController.formEdit()发生异常：" + e.getMessage(), e);
			return Result.error("修改失败，" + CgformSqlUtil.parseException(e));
		}
	}

	@AutoLog(
			operateType = 4,
			value = "online删除数据",
			module = ModuleType.ONLINE
	)
	@OnlineAuth("form")
	@DeleteMapping({"/form/{code}/{id}"})
	public Result<?> deleteForm(@PathVariable("code") String code, @PathVariable("id") String id) {
		OnlCgformHead one = (OnlCgformHead) this.onlCgformHeadService.getById(code);
		if (one == null) {
			return Result.error("实体不存在");
		} else {
			try {
				String pidStr = "";
				if ("Y".equals(one.getIsTree())) {
					id = this.onlCgformFieldService.queryTreeChildIds(one, id);
					pidStr = this.onlCgformFieldService.queryTreePids(one, id);
				}

				if (id.indexOf(",") > 0) {
					String tableName;
					if (one.getTableType() == 2) {
						this.onlCgformFieldService.deleteAutoListMainAndSub(one, id);
					} else {
						tableName = one.getTableName();
						this.onlCgformFieldService.deleteAutoListById(tableName, id);
					}

					if ("Y".equals(one.getIsTree())) {
						tableName = one.getTableName();
						String treeIdField = one.getTreeIdField();
						String[] pids = pidStr.split(",");
						int length = pids.length;

						for (int i = 0; i < length; ++i) {
							String pid = pids[i];
							this.onlCgformFieldService.updateTreeNodeNoChild(tableName, treeIdField, pid);
						}
					}
				} else {
					this.onlCgformHeadService.deleteOneTableInfo(code, id);
				}
			} catch (Exception var12) {
				log.error("OnlCgformApiController.formEdit()发生异常：" + var12.getMessage(), var12);
				return Result.error("删除失败");
			}

			Result result = Result.ok("删除成功!");
			result.setOnlTable(one.getTableName());
			return result;
		}
	}

	/**
	 * 此a处可能有问题 ：/formByCode/{code}/{id}？？
	 *
	 * @param code
	 * @param id
	 * @return
	 */
	@AutoLog(
			operateType = 4,
			value = "online删除数据",
			module = ModuleType.ONLINE
	)
	@DeleteMapping({"/formByCode/{code}/{id}"})
	public Result<?> formByCode(@PathVariable("code") String code, @PathVariable("id") String id) {
		OnlCgformHead one = this.onlCgformHeadService.getOne(Wrappers.lambdaQuery(OnlCgformHead.class).eq(OnlCgformHead::getTableName, code));
		if (one == null) {
			return Result.error("实体不存在");
		} else {
			try {
				if (id.indexOf(",") > 0) {
					String tableName = one.getTableName();
					this.onlCgformFieldService.deleteAutoListById(tableName, id);
				} else {
					this.onlCgformHeadService.deleteOneTableInfo(one.getId(), id);
				}
			} catch (Exception e) {
				log.error("OnlCgformApiController.formEdit()发生异常：" + e.getMessage(), e);
				return Result.error("删除失败");
			}

			Result result = Result.ok("删除成功!");
			result.setOnlTable(one.getTableName());
			return result;
		}
	}

	@OnlineAuth("getQueryInfo")
	@GetMapping({"/getQueryInfo/{code}"})
	public Result<?> getQueryInfob(@PathVariable("code") String code) {
		try {
			List list = this.onlCgformFieldService.getAutoListQueryInfo(code);
			return Result.ok(list);
		} catch (Exception e) {
			log.error("OnlCgformApiController.getQueryInfo()发生异常：" + e.getMessage(), e);
			return Result.error("查询失败");
		}
	}

	@PostMapping({"/doDbSynch/{code}/{synMethod}"})
	public Result<?> doDbSynch(@PathVariable("code") String code, @PathVariable("synMethod") String synMethod) {
		try {
			long timeMillis = System.currentTimeMillis();
			this.onlCgformHeadService.doDbSynch(code, synMethod);
			log.info("==同步数据库消耗时间" + (System.currentTimeMillis() - timeMillis) + "毫秒");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("同步数据库失败，" + CgformSqlUtil.parseException(e));
		}

		return Result.ok("同步数据库成功!");
	}

	@OnlineAuth("exportXls")
	@PermissionData
	@GetMapping({"/exportXls/{code}"})
	public void exportXls(@PathVariable("code") String code, HttpServletRequest req, HttpServletResponse res) {
		OnlCgformHead one = (OnlCgformHead) this.onlCgformHeadService.getById(code);
		if (one != null) {
			String tableTxt = one.getTableTxt();
			String paramsStr = req.getParameter("paramsStr");
			Object obj = new HashMap();
			String s = null;
			if (oConvertUtils.isNotEmpty(paramsStr)) {
				try {
					s = URLDecoder.decode(paramsStr, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					log.error(e.getMessage(), e);
				}

				if (s != null) {
					obj = (Map) JSONObject.parseObject(s, Map.class);
				}
			}

			((Map) obj).put("pageSize", -521);
			Map map = this.onlCgformFieldService.queryAutolistPage(one.getTableName(), one.getId(), (Map) obj, (List) null);
			List fieldList = (List) map.get("fieldList");
			List<Map<String, Object>> records = (List<Map<String, Object>>) map.get("records");
			Object datalist = new ArrayList();
			String selections = null;
			if(((Map) obj).get("selections") != null){
				selections = ((Map) obj).get("selections").toString();
			}
			if (oConvertUtils.isNotEmpty(selections)) {
				final List selectionslist = Arrays.asList(selections.split(","));
				List<Map<String, Object>> ids = records.stream().filter(a -> selectionslist.contains(a.get("id"))).collect(Collectors.toList());
				map.put("records",ids);
			} else {
				if (records == null) {
					records = new ArrayList();
				}

				((List) datalist).addAll((Collection) records);
			}

			ValueFillConverter.a(1, (List) datalist, fieldList);

			try {
				this.onlCgformHeadService.executeEnhanceExport(one, (List) datalist);
			} catch (BusinessException var32) {
				log.error("导出java增强处理出错", var32.getMessage());
			}

			List var14 = this.a(fieldList, "id");
			if (one.getTableType() == 2 && oConvertUtils.isEmpty(((Map) obj).get("exportSingleOnly"))) {
				String tableStr = one.getSubTableStr();
				if (oConvertUtils.isNotEmpty(tableStr)) {
					String[] tables = tableStr.split(",");
					int length = tables.length;

					for (int i = 0; i < length; ++i) {
						String table = tables[i];
						this.a(table, (Map) obj, (List) datalist, var14);
					}
				}
			}

			Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams((String) null, tableTxt), var14, (Collection) datalist);
			ServletOutputStream stream = null;

			try {
				res.setContentType("application/x-msdownload;charset=utf-8");
				String browse = BrowserUtils.checkBrowse(req);
				//名字处理
				String txtName = one.getTableTxt() + "-v" + one.getTableVersion();
				if ("MSIE".equalsIgnoreCase(browse.substring(0, 4))) {
					res.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(txtName, "UTF-8") + ".xls");
				} else {
					String filedName = new String(txtName.getBytes("UTF-8"), "ISO8859-1");
					res.setHeader("content-disposition", "attachment;filename=" + filedName + ".xls");
				}

				stream = res.getOutputStream();
				workbook.write(stream);
				res.flushBuffer();
			} catch (Exception e) {
				log.error("--通过流的方式获取文件异常--" + e.getMessage(), e);
			} finally {
				if (stream != null) {
					try {
						stream.close();
					} catch (IOException e) {
						log.error(e.getMessage(), e);
					}
				}

			}

		}
	}

	/**
	 * 导出excel.xls
	 * @param code
	 * @param req
	 * @param res
	 * @return
	 */
	@OnlineAuth("importXls")
	@PostMapping({"/importXls/{code}"})
	public Result<?> importXls(@PathVariable("code") String code, HttpServletRequest req, HttpServletResponse res) {
		InputStream isr = null;
		long timeMillis = System.currentTimeMillis();
		Result result = new Result();
		String var7 = "";

		try {
			OnlCgformHead one = this.onlCgformHeadService.getById(code);
			if (one == null) {
				return Result.error("数据库不存在该表记录");
			}

			LambdaQueryWrapper<OnlCgformField> wrapper = new LambdaQueryWrapper();
			wrapper.eq(OnlCgformField::getCgformHeadId, code);
			List dataList = this.onlCgformFieldService.list(wrapper);
			String var11 = req.getParameter("isSingleTableImport");
			List var12 = CgformSqlUtil.parseImage(dataList);
			if (oConvertUtils.isEmpty(var11) && one.getTableType() == 2 && oConvertUtils.isNotEmpty(one.getSubTableStr())) {
				String[] var13 = one.getSubTableStr().split(",");
				int var14 = var13.length;

				for (int var15 = 0; var15 < var14; ++var15) {
					String var16 = var13[var15];
					OnlCgformHead var17 = this.onlCgformHeadService.getOne(Wrappers.lambdaQuery(OnlCgformHead.class).eq(OnlCgformHead::getTableName, var16));
					if (var17 != null) {
						List var18 = this.onlCgformFieldService.list(Wrappers.lambdaQuery(OnlCgformField.class).eq(OnlCgformField::getCgformHeadId, var17.getId()));
						List var19 = CgformSqlUtil.parseImage(var18, var17.getTableTxt());
						if (var19.size() > 0) {
							var12.addAll(var19);
						}
					}
				}
			}

			JSONObject var47 = null;
			String var48 = req.getParameter("foreignKeys");
			if (oConvertUtils.isNotEmpty(var48)) {
				var47 = JSONObject.parseObject(var48);
			}

			MultipartHttpServletRequest var49 = (MultipartHttpServletRequest) req;
			Map var50 = var49.getFileMap();
			DataSource dataSource=SpringContextUtils.getApplicationContext().getBean(DataSource.class);
			String var52 = DialectUtil.getDataType(dataSource);
			Iterator var53 = var50.entrySet().iterator();

			while (true) {
				while (var53.hasNext()) {
					Entry var20 = (Entry) var53.next();
					MultipartFile var21 = (MultipartFile) var20.getValue();
					ImportParams var22 = new ImportParams();
					var22.setImageList(var12);
					var22.setDataHanlder(new ExcelDataHandlerDefaultUtil(dataList, this.upLoadPath, this.uploadType));
					isr = var21.getInputStream();
					List var23 = ExcelImportUtil.importExcel(isr, Map.class, var22);
					if (var23 != null) {
						Object var24 = "";
						ArrayList var25 = new ArrayList();

						Map var27;
						for (Iterator var26 = var23.iterator(); var26.hasNext(); var27.put("$mainTable$id", var24)) {
							var27 = (Map) var26.next();
							boolean var28 = false;
							Set var29 = var27.keySet();
							HashMap var30 = new HashMap();
							Iterator var31 = var29.iterator();

							String var32;
							while (var31.hasNext()) {
								var32 = (String) var31.next();
								if (var32.indexOf("$subTable$") == -1) {
									if (var32.indexOf("$mainTable$") != -1 && oConvertUtils.isNotEmpty(var27.get(var32).toString())) {
										var28 = true;
										var24 = this.getTableId(one, dataSource, var52);
									}

									var30.put(var32.replace("$mainTable$", ""), var27.get(var32));
								}
							}

							if (var28) {
								var30.put("id", var24);
								var25.add(var30);
								var24 = var30.get("id");
							}

							if (var47 != null) {
								var31 = var47.keySet().iterator();

								while (var31.hasNext()) {
									var32 = (String) var31.next();
									var30.put(var32, var47.getString(var32));
								}
							}
						}

						if (var25 == null || var25.size() == 0) {
							result.setSuccess(false);
							result.setMessage("导入失败，匹配的数据条数为零!");
							return result;
						}

						this.onlCgformSqlService.saveBatchOnlineTable(one, dataList, var25);
						if (oConvertUtils.isEmpty(var11) && one.getTableType() == 2 && oConvertUtils.isNotEmpty(one.getSubTableStr())) {
							String[] var54 = one.getSubTableStr().split(",");
							int var55 = var54.length;

							for (int var56 = 0; var56 < var55; ++var56) {
								String var57 = var54[var56];
								OnlCgformHead var58 = (OnlCgformHead) this.onlCgformHeadService.getOne((Wrappers.lambdaQuery(OnlCgformHead.class).eq(OnlCgformHead::getTableName, var57)));
								if (var58 != null) {
									LambdaQueryWrapper<OnlCgformField> var59 = new LambdaQueryWrapper();
									var59.eq(OnlCgformField::getCgformHeadId, var58.getId());
									List var60 = this.onlCgformFieldService.list(var59);
									ArrayList var33 = new ArrayList();
									String var34 = var58.getTableTxt();
									Iterator var35 = var23.iterator();

									while (var35.hasNext()) {
										Map var36 = (Map) var35.next();
										boolean var37 = false;
										HashMap var38 = new HashMap();
										Iterator var39 = var60.iterator();

										while (var39.hasNext()) {
											OnlCgformField var40 = (OnlCgformField) var39.next();
											String var41 = var40.getMainTable();
											String var42 = var40.getMainField();
											boolean var43 = one.getTableName().equals(var41) && oConvertUtils.isNotEmpty(var42);
											String var44 = var34 + "_" + var40.getDbFieldTxt();
											if (var43) {
												var38.put(var40.getDbFieldName(), var36.get("$mainTable$" + var42));
											}

											Object var45 = var36.get("$subTable$" + var44);
											if (null != var45 && oConvertUtils.isNotEmpty(var45.toString())) {
												var37 = true;
												var38.put(var40.getDbFieldName(), var45);
											}
										}

										if (var37) {
											var38.put("id", this.getTableId(var58, dataSource, var52));
											var33.add(var38);
										}
									}

									if (var33.size() > 0) {
										this.onlCgformSqlService.saveBatchOnlineTable(var58, var60, var33);
									}
								}
							}
						}

						var7 = "文件导入成功！";
					} else {
						var7 = "识别模版数据错误";
						log.error(var7);
					}
				}

				result.setSuccess(true);
				result.setMessage("导入成功!");
				break;
			}
		} catch (Exception var46) {
			result.setSuccess(false);
			result.setMessage(var46.getMessage());
			log.error(var46.getMessage(), var46);
		} finally {
			if (isr != null) {
				try {
					isr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		log.info("=====online导入数据完成,耗时:" + (System.currentTimeMillis() - timeMillis) + "毫秒=====");
		return result;
	}

	@PostMapping({"/doButton"})
	public Result<?> doButton(@RequestBody JSONObject jsonObject) {
		String formId = jsonObject.getString("formId");
		String dataId = jsonObject.getString("dataId");
		String buttonCode = jsonObject.getString("buttonCode");
		JSONObject uiFormData = jsonObject.getJSONObject("uiFormData");

		try {
			this.onlCgformHeadService.executeCustomerButton(buttonCode, formId, dataId);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("执行失败!");
		}

		return Result.ok("执行成功!");
	}

	//
	public Object getTableId(OnlCgformHead var1, DataSource dataSource, String var3) throws SQLException, DBException {
		Object var4 = null;
		String var5 = var1.getIdType();
		String var6 = var1.getIdSequence();
		if (oConvertUtils.isNotEmpty(var5) && "UUID".equalsIgnoreCase(var5)) {
			var4 = CgformSqlUtil.getId();
		} else {
			PostgresSequenceMaxValueIncrementer var7;
			OracleSequenceMaxValueIncrementer var13;
			if (oConvertUtils.isNotEmpty(var5) && "NATIVE".equalsIgnoreCase(var5)) {
				if (oConvertUtils.isNotEmpty(var3) && "oracle".equalsIgnoreCase(var3)) {
					var13 = new OracleSequenceMaxValueIncrementer(dataSource, "HIBERNATE_SEQUENCE");

					try {
						var4 = var13.nextLongValue();
					} catch (Exception var12) {
						log.error(var12.getMessage(), var12);
					}
				} else if (oConvertUtils.isNotEmpty(var3) && "postgres".equalsIgnoreCase(var3)) {
					var7 = new PostgresSequenceMaxValueIncrementer(dataSource, "HIBERNATE_SEQUENCE");

					try {
						var4 = var7.nextLongValue();
					} catch (Exception var11) {
						log.error(var11.getMessage(), var11);
					}
				} else {
					var4 = null;
				}
			} else if (oConvertUtils.isNotEmpty(var5) && "SEQUENCE".equalsIgnoreCase(var5)) {
				if (oConvertUtils.isNotEmpty(var3) && "oracle".equalsIgnoreCase(var3)) {
					var13 = new OracleSequenceMaxValueIncrementer(dataSource, var6);

					try {
						var4 = var13.nextLongValue();
					} catch (Exception var10) {
						log.error(var10.getMessage(), var10);
					}
				} else if (oConvertUtils.isNotEmpty(var3) && "postgres".equalsIgnoreCase(var3)) {
					var7 = new PostgresSequenceMaxValueIncrementer(dataSource, var6);

					try {
						var4 = var7.nextLongValue();
					} catch (Exception var9) {
						log.error(var9.getMessage(), var9);
					}
				} else {
					var4 = null;
				}
			} else {
				var4 = CgformSqlUtil.getId();
			}
		}

		return var4;
	}

	private void a(Map var1, List<OnlCgformField> var2) {
		Iterator var3 = var2.iterator();

		while (true) {
			OnlCgformField var4;
			String var5;
			String var6;
			String var7;
			do {
				do {
					if (!var3.hasNext()) {
						return;
					}

					var4 = (OnlCgformField) var3.next();
					var5 = var4.getDictTable();
					var6 = var4.getDictField();
					var7 = var4.getDictText();
				} while (oConvertUtils.isEmpty(var5) && oConvertUtils.isEmpty(var6));
			} while ("popup".equals(var4.getFieldShowType()));

			String var9 = String.valueOf(var1.get(var4.getDbFieldName()));
			List var8;
			if (oConvertUtils.isEmpty(var5)) {
				var8 = this.sysBaseAPI.queryDictItemsByCode(var6);
			} else {
				var8 = this.sysBaseAPI.queryTableDictItemsByCode(var5, var7, var6);
			}

			Iterator var10 = var8.iterator();

			while (var10.hasNext()) {
				DictModel var11 = (DictModel) var10.next();
				if (var9.equals(var11.getText())) {
					var1.put(var4.getDbFieldName(), var11.getValue());
				}
			}
		}
	}

	/**
	 *
	 * @param var1
	 * @param var2
	 * @return
	 */
	private List<ExcelExportEntity> a(List<OnlCgformField> var1, String var2) {
		ArrayList var3 = new ArrayList();

		for (int var4 = 0; var4 < var1.size(); ++var4) {
			if ((null == var2 || !var2.equals(((OnlCgformField) var1.get(var4)).getDbFieldName())) && ((OnlCgformField) var1.get(var4)).getIsShowList() == 1) {
				String var5 = ((OnlCgformField) var1.get(var4)).getDbFieldName();
				ExcelExportEntity var6 = new ExcelExportEntity(((OnlCgformField) var1.get(var4)).getDbFieldTxt(), var5);
				if ("image".equals(((OnlCgformField) var1.get(var4)).getFieldShowType())) {
					var6.setType(2);
					var6.setExportImageType(3);
					var6.setImageBasePath(this.upLoadPath);
					var6.setHeight(50.0D);
					var6.setWidth(60.0D);
				} else {
					int var7 = ((OnlCgformField) var1.get(var4)).getDbLength() == 0 ? 12 : (((OnlCgformField) var1.get(var4)).getDbLength() > 30 ? 30 : ((OnlCgformField) var1.get(var4)).getDbLength());
					if (((OnlCgformField) var1.get(var4)).getFieldShowType().equals("date")) {
						var6.setFormat("yyyy-MM-dd");
					} else if (((OnlCgformField) var1.get(var4)).getFieldShowType().equals("datetime")) {
						var6.setFormat("yyyy-MM-dd HH:mm:ss");
					}

					if (var7 < 10) {
						var7 = 10;
					}

					var6.setWidth((double) var7);
				}

				var3.add(var6);
			}
		}

		return var3;
	}

	/**
	 *
	 * @param var1
	 * @param map
	 * @param list
	 * @param var4
	 */
	private void a(String var1, Map<String, Object> map, List<Map<String, Object>> list, List<ExcelExportEntity> var4) {
		OnlCgformHead var5 = (OnlCgformHead) this.onlCgformHeadService.getOne(Wrappers.lambdaQuery(OnlCgformHead.class).eq(OnlCgformHead::getTableName, var1));
		LambdaQueryWrapper<OnlCgformField> var6 = new LambdaQueryWrapper();
		var6.eq(OnlCgformField::getCgformHeadId, var5.getId());
		var6.orderByAsc(OnlCgformField::getOrderNum);
		List var7 = this.onlCgformFieldService.list(var6);
		String var8 = "";
		String var9 = "";
		Iterator var10 = var7.iterator();

		while (var10.hasNext()) {
			OnlCgformField var11 = (OnlCgformField) var10.next();
			if (oConvertUtils.isNotEmpty(var11.getMainField())) {
				var8 = var11.getMainField();
				var9 = var11.getDbFieldName();
				break;
			}
		}

		ExcelExportEntity var14 = new ExcelExportEntity(var5.getTableTxt(), var1);
		var14.setList(this.a(var7, "id"));
		var4.add(var14);

		for (int var15 = 0; var15 < list.size(); ++var15) {
			map.put(var9, ((Map) list.get(var15)).get(var8));
			String var12 = CgformSqlUtil.searchSql(var5.getTableName(), var7, map);
			log.info("-----------动态列表查询子表sql》》" + var12);
			List var13 = this.onlCgformHeadService.queryListData(var12);
			ValueFillConverter.a(1, var13, var7);
			((Map) list.get(var15)).put(var1, CgformSqlUtil.parseData(var13));
		}

	}

	@GetMapping({"/checkOnlyTable"})
	public Result<?> checkOnlyTablei(@RequestParam("tbname") String tbname, @RequestParam("id") String id) {
		OnlCgformHead cgformHead;
		if (oConvertUtils.isEmpty(id)) {
			if (DialectUtil.isTableExists(tbname)) {
				return Result.ok(-1);
			}

			cgformHead = (OnlCgformHead) this.onlCgformHeadService.getOne(Wrappers.lambdaQuery(OnlCgformHead.class).eq(OnlCgformHead::getTableName, tbname));
			if (oConvertUtils.isNotEmpty(cgformHead)) {
				return Result.ok(-1);
			}
		} else {
			cgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(id);
			if (!tbname.equals(cgformHead.getTableName()) && DialectUtil.isTableExists(tbname)) {
				return Result.ok(-1);
			}
		}

		return Result.ok(1);
	}

	@PostMapping({"/codeGenerate"})
	public Result<?> codeGenerate(@RequestBody JSONObject var1) throws AppException {
		OnlGenerateModel var2 = (OnlGenerateModel) JSONObject.parseObject(var1.toJSONString(), OnlGenerateModel.class);
		List fileList = new ArrayList();
		try {
			if ("1".equals(var2.getJformType())) {
				fileList.add(zipFile(this.onlCgformHeadService.generateCode(var2)));
			} else {
				fileList.add(zipFile( this.onlCgformHeadService.generateOneToMany(var2)));
			}
			return Result.ok(fileList);
		} catch (Exception var5) {
			var5.printStackTrace();
			return Result.error(var5.getMessage());
		}
	}
	private  String zipFile(List<String> fileList) throws AppException
	{
		List list =fileList.stream().filter((var0) -> {
			return var0.indexOf("src/main/java") == -1 && var0.indexOf("src%5Cmain%5Cjava") == -1;
		}).collect(Collectors.toList());
		if (fileList != null && (list == null || list.size() <= 0)) {
			String var5 = "生成代码_" + System.currentTimeMillis() + ".zip";
			final String var6 = this.generatePath+ var5;
			File var7 = ZipUtils.zip(fileList, var6);
			return var7.getAbsolutePath();
		} else {
			throw new AppException(" fileList 不合法！！！");
		}
	}

	/**
	 * 代理扫描路径遍历-漏洞修复
	 */
	private static Pattern FilePattern = Pattern.compile("[\\\\/:*?\"<>|]");
	public static String fileNameFilter(String str){
		return str==null?null:FilePattern.matcher(str).replaceAll("");
	}
	/**
	 * downGenerateCode
	 * @param fileList
	 * @param req
	 * @param res
	 */
	@GetMapping({"/downGenerateCode"})
	public void downGenerateCode(@RequestParam("fileList") List<String> fileList, HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException {
		String filePath = fileNameFilter(URLDecoder.decode(fileList.get(0), "UTF-8"));
		File  file =new File(filePath);

		if (file.exists()) {
			res.setContentType("application/force-download");
			//代码扫描
			String fileName = file.getName().replaceAll("(\r\n|\r|\n|\n\r)","");
			res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
			byte[] var8 = new byte[1024];
			try(BufferedInputStream var10=new BufferedInputStream(new FileInputStream(file)) ){
				ServletOutputStream var11 = res.getOutputStream();
				for (int var12 = var10.read(var8); var12 != -1; var12 = var10.read(var8)) {
					var11.write(var8, 0, var12);
				}
			} catch (FileNotFoundException e) {
				log.error(e.getMessage(),e);
			} catch (IOException e) {
				log.error(e.getMessage(),e);
			}
		}
	}

	@AutoLog(
			operateType = 1,
			value = "online列表数据查询",
			module = ModuleType.ONLINE
	)
	@GetMapping({"/getTreeData/{code}"})
	@PermissionData
	public Result<Map<String, Object>> getTreeData(@PathVariable("code") String code, HttpServletRequest request) {
		Result var3 = new Result();
		OnlCgformHead var4 = (OnlCgformHead) this.onlCgformHeadService.getById(code);
		if (var4 == null) {
			var3.error500("实体不存在");
			return var3;
		} else {
			try {
				String var5 = var4.getTableName();
				String var6 = var4.getTreeIdField();
				String var7 = var4.getTreeParentIdField();
				ArrayList var8 = Lists.newArrayList(new String[]{var6, var7});
				Map var9 = CgformSqlUtil.paramToMap(request);
				String var10 = null;
				if (var9.get(var6) != null) {
					var10 = var9.get(var6).toString();
				}

				if (var9.get("hasQuery") != null && "false".equals(var9.get("hasQuery")) && var9.get(var7) == null) {
					var9.put(var7, "0");
				} else {
					var9.put("pageSize", -521);
					var9.put(var7, var9.get(var7));
				}

				var9.put(var6, (Object) null);
				Map var11 = this.onlCgformFieldService.queryAutoTreeNoPage(var5, code, var9, var8, var7);
				this.executeEnhanceList(var4, var11);
				var3.setResult(var11);
			} catch (Exception var12) {
				log.error(var12.getMessage(), var12);
				var3.error500("数据库查询失败" + var12.getMessage());
			}

			var3.setOnlTable(var4.getTableName());
			return var3;
		}
	}
	//封装的getTreeData
	private void executeEnhanceList(OnlCgformHead onlCgformHead, Map<String, Object> map) throws BusinessException {
		List records = (List) map.get("records");
		//
		this.onlCgformHeadService.executeEnhanceList(onlCgformHead, "query", records);
	}

	@PostMapping({"/crazyForm/{name}"})
	public Result<?> crazyFormPost(@PathVariable("name") String name, @RequestBody JSONObject jobj) {
		Result result = new Result();

		try {
			String a = CgformSqlUtil.getId();
			jobj.put("id", a);
			this.onlCgformHeadService.addCrazyFormData(name, jobj);
			result.setResult(a);
			result.setMessage("保存成功");
			return result;
		} catch (Exception e) {
			log.error("OnlCgformApiController.formAddForDesigner()发生异常：" + e.getMessage(), e);
			return Result.error("保存失败");
		}
	}

	/**
	 *
	 * @param name
	 * @param jobj
	 * @return
	 */
	@PutMapping({"/crazyForm/{name}"})
	public Result<?> crazyFormPut(@PathVariable("name") String name, @RequestBody JSONObject jobj) {
		try {
			this.onlCgformHeadService.editCrazyFormData(name, jobj);
		} catch (Exception e) {
			log.error("OnlCgformApiController.formEditForDesigner()发生异常：" + e.getMessage(), e);
			return Result.error("保存失败");
		}

		return Result.ok("保存成功!");
	}

	@AutoLog(
			operateType = 1,
			value = "online列表加载",
			module = ModuleType.ONLINE
	)
	@GetMapping({"/getErpColumns/{code}"})
	public Result<Map<String, Object>> getErpColumns(@PathVariable("code") String code) {
		Result result = new Result();
		OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(code);
		if (onlCgformHead == null) {
			result.error500("实体不存在");
			return result;
		} else {
			HashMap map = new HashMap();
			//静态内部类
			OnlForeignKey.OnlComplexModel inner = this.onlineService.queryOnlineConfig(onlCgformHead);
			map.put("main", inner);
			if ("erp".equals(onlCgformHead.getThemeTemplate()) && onlCgformHead.getTableType() == 2) {
				String tableStr = onlCgformHead.getSubTableStr();
				if (oConvertUtils.isNotEmpty(tableStr)) {
					ArrayList list = new ArrayList();
					String[] tables = tableStr.split(",");
					int length = tables.length;

					for (int i = 0; i < length; ++i) {
						String str = tables[i];
						OnlCgformHead head = (OnlCgformHead) this.onlCgformHeadService.getOne(Wrappers.lambdaQuery(OnlCgformHead.class).eq(OnlCgformHead::getTableName, str));
						if (head != null) {
							list.add(this.onlineService.queryOnlineConfig(head));
						}
					}

					if (list.size() > 0) {
						map.put("subList", list);
					}
				}
			}

			result.setOnlTable(onlCgformHead.getTableName());
			result.setResult(map);
			result.setSuccess(true);
			return result;
		}
	}

	@AutoLog(
			operateType = 1,
			value = "online表单加载",
			module = ModuleType.ONLINE
	)
	@GetMapping({"/getErpFormItem/{code}"})
	public Result<?> getErpFormItem(@PathVariable("code") String code, HttpServletRequest request) {
		OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(code);
		if (onlCgformHead == null) {
			return Result.error("表不存在");
		}

		Result result = new Result();
		JSONObject jsonObject = this.onlineService.queryOnlineFormObj(onlCgformHead);
		result.setResult(jsonObject);
		result.setOnlTable(onlCgformHead.getTableName());
		return result;
	}

	@GetMapping({"/querySelectOptions"})
	public Result<List<TreeModel>> querySelectOptions(@ModelAttribute TableComponent tableComponent) {
		Result result = new Result();
		List list = this.onlCgformFieldService.queryDataListByLinkDown(tableComponent);
		result.setResult(list);
		result.setSuccess(true);
		return result;
	}
}
